package com.rnkrsoft.suyan.config.server.services.impl;

import com.rnkrsoft.framework.orm.Pagination;
import com.rnkrsoft.suyan.config.internal.enums.EnvironmentStatusEnum;
import com.rnkrsoft.suyan.config.internal.enums.OperateObjectEnum;
import com.rnkrsoft.suyan.config.internal.enums.OperateTypeEnum;
import com.rnkrsoft.suyan.config.protocol.v2.ConfigResponseCode;
import com.rnkrsoft.suyan.config.server.config.dao.*;
import com.rnkrsoft.suyan.config.server.config.bo.*;
import com.rnkrsoft.suyan.config.server.config.entity.*;
import com.rnkrsoft.suyan.config.server.services.environment.domains.*;
import com.rnkrsoft.suyan.config.server.services.environment.services.EnvironmentService;
import com.rnkrsoft.suyan.config.server.services.logger.services.LoggerService;
import com.rnkrsoft.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.doc.data.item.OptionItem;
import java.util.List;


/**
 * Created by woate on 2018/6/18.
 */
@Service
public class EnvironmentServiceImpl implements EnvironmentService {
    @Autowired
    ProjectInfoDAO projectDAO;
    @Autowired
    ProjectDependencyDAO projectDependencyDAO;
    @Autowired
    VersionInfoDAO versionInfoDAO;
    @Autowired
    EnvironmentInfoDAO environmentDAO;
    @Autowired
    MachineInfoDAO machineInfoDAO;
    @Autowired
    ParamInfoDAO paramInfoDAO;
    @Autowired
    FileInfoDAO fileInfoDAO;
    @Autowired
    LoggerService loggerService;

    @Override
    public CreateEnvironmentResponse create(CreateEnvironmentRequest request) {
        CreateEnvironmentResponse response = new CreateEnvironmentResponse();
        VersionInfoEntity versionInfoEntity = versionInfoDAO.selectByPrimaryKey(request.getVersionId());
        List<VersionInfoEntity> versionInfoEntities = versionInfoDAO.selectDependencyVersion(versionInfoEntity.getProjectId(), versionInfoEntity.getVersion());
        for (VersionInfoEntity record : versionInfoEntities){
            int cnt = environmentDAO.countAnd(EnvironmentInfoEntity.builder()
                    .versionId(record.getVersionId())
                    .environmentName(request.getEnvironmentName())
                    .build()
            );
            if (cnt == 0 ) {
                EnvironmentInfoEntity environment = EnvironmentInfoEntity.builder()
                        .versionId(record.getVersionId())
                        .projectId(record.getProjectId())
                        .environmentType(request.getEnvironmentType())
                        .environmentName(request.getEnvironmentName())
                        .environmentDesc(request.getEnvironmentDesc())
                        .environmentStatus(EnvironmentStatusEnum.NORMAL.getCode())
                        .build();
                environmentDAO.insertSelective(environment);
            }
        }
        List<EnvironmentInfoEntity> environmentInfoEntities = environmentDAO.selectAnd(EnvironmentInfoEntity.builder().versionId(request.getVersionId()).build());
        if (!environmentInfoEntities.isEmpty()) {
            response.updateResult(ConfigResponseCode.NO_DATA);
            return response;
        }
        EnvironmentInfoEntity environmentEntity = EnvironmentInfoEntity.builder()
                .versionId(versionInfoEntity.getVersionId())
                .projectId(versionInfoEntity.getProjectId())
                .environmentType(request.getEnvironmentType())
                .environmentName(request.getEnvironmentName())
                .environmentDesc(request.getEnvironmentDesc())
                .environmentStatus(EnvironmentStatusEnum.NORMAL.getCode())
                .build();
        environmentDAO.insertSelective(environmentEntity);
        response.setEnvironmentId(environmentEntity.getEnvironmentId());
        return response;
    }

    @Override
    public ToUpdateEnvironmentResponse toUpdate(ToUpdateEnvironmentRequest request) {
        ToUpdateEnvironmentResponse response = new ToUpdateEnvironmentResponse();
        EnvironmentInfoEntity environmentEntity = environmentDAO.selectByPrimaryKey(request.getEnvironmentId());
        if (environmentEntity == null) {
            response.updateResult(ConfigResponseCode.NO_DATA);
            return response;
        }
        VersionInfoEntity versionInfoEntity = versionInfoDAO.selectByPrimaryKey(environmentEntity.getVersionId());
        if (versionInfoEntity == null) {
            response.updateResult(ConfigResponseCode.NO_DATA);
            return response;
        }
        ProjectInfoEntity projectInfoEntity = projectDAO.selectByPrimaryKey(versionInfoEntity.getProjectId());
        if (projectInfoEntity == null) {
            response.updateResult(ConfigResponseCode.NO_DATA);
            return response;
        }
        response.setProject(projectInfoEntity.getProjectDesc() + "(" + projectInfoEntity.getGroupId() + ":" + projectInfoEntity.getArtifactId() + ":" + versionInfoEntity.getVersion() + ")");
        response.setEnvironmentId(environmentEntity.getEnvironmentId());
        response.setEnvironmentName(environmentEntity.getEnvironmentName());
        response.setEnvironmentType(environmentEntity.getEnvironmentType());
        response.setEnvironmentDesc(environmentEntity.getEnvironmentDesc());
        return response;
    }

    @Override
    public UpdateEnvironmentResponse update(UpdateEnvironmentRequest request) {
        UpdateEnvironmentResponse response = new UpdateEnvironmentResponse();
        EnvironmentInfoEntity environmentEntity = environmentDAO.selectByPrimaryKey(request.getEnvironmentId());
        if (environmentEntity == null) {
            response.updateResult(ConfigResponseCode.NO_DATA);
            return response;
        }
        environmentEntity.setEnvironmentName(request.getEnvironmentName());
        environmentEntity.setEnvironmentType(request.getEnvironmentType());
        environmentEntity.setEnvironmentDesc(request.getEnvironmentDesc());

        loggerService.writeLog(OperateObjectEnum.ENVIRONMENT, request.getEnvironmentId(), OperateTypeEnum.UPDATE, request.getLoginUserId(), request.getLoginUserName());


        environmentDAO.updateByPrimaryKeySelective(environmentEntity);
        return response;
    }

    @Override
    public DeleteEnvironmentResponse delete(DeleteEnvironmentRequest request) {
        DeleteEnvironmentResponse response = new DeleteEnvironmentResponse();

        loggerService.writeLog(OperateObjectEnum.ENVIRONMENT, request.getEnvironmentId(), OperateTypeEnum.UPDATE, request.getLoginUserId(), request.getLoginUserName());

        environmentDAO.deleteByPrimaryKey(request.getEnvironmentId());
        machineInfoDAO.deleteAnd(MachineInfoEntity.builder().environmentId(request.getEnvironmentId()).build());
        paramInfoDAO.deleteAnd(ParamInfoEntity.builder().environmentId(request.getEnvironmentId()).build());
        fileInfoDAO.deleteAnd(FileInfoEntity.builder().environmentId(request.getEnvironmentId()).build());
        return response;
    }

    @Override
    public ViewEnvironmentResponse view(ViewEnvironmentRequest request) {
        ViewEnvironmentResponse response = new ViewEnvironmentResponse();
        EnvironmentInfoEntity environmentEntity = environmentDAO.selectByPrimaryKey(request.getEnvironmentId());
        if (environmentEntity == null) {
            response.updateResult(ConfigResponseCode.NO_DATA);
            return response;
        }
        VersionInfoEntity versionInfoEntity = versionInfoDAO.selectByPrimaryKey(environmentEntity.getVersionId());
        if (versionInfoEntity == null) {
            response.updateResult(ConfigResponseCode.NO_DATA);
            return response;
        }
        ProjectInfoEntity projectInfoEntity = projectDAO.selectByPrimaryKey(versionInfoEntity.getProjectId());
        if (projectInfoEntity == null) {
            response.updateResult(ConfigResponseCode.NO_DATA);
            return response;
        }
        response.setProject(projectInfoEntity.getProjectDesc() + "(" + projectInfoEntity.getGroupId() + ":" + projectInfoEntity.getArtifactId() + ":" + versionInfoEntity.getVersion() + ")");
        response.setEnvironmentId(request.getEnvironmentId());
        response.setEnvironmentName(environmentEntity.getEnvironmentName());
        response.setEnvironmentType(environmentEntity.getEnvironmentType());
        response.setEnvironmentDesc(environmentEntity.getEnvironmentDesc());
        return response;
    }

    @Override
    public QueryEnvironmentResponse query(QueryEnvironmentRequest request) {
        QueryEnvironmentResponse response = new QueryEnvironmentResponse();
        Pagination<QueryEnvironmentInfoBO> pagination = new Pagination<QueryEnvironmentInfoBO>(request.getPagination().getPageSize(), request.getPagination().getPageNo());
        if (StringUtils.isNotBlank(request.getProjectId())) {
            pagination.getParams().put("projectId", request.getProjectId());
        }
        if (StringUtils.isNotBlank(request.getProjectId())) {
            pagination.getParams().put("version", request.getVersion());
        }
        if (StringUtils.isNotBlank(request.getEnvironmentType())){
            pagination.getParams().put("environmentType", request.getEnvironmentType());
        }
        if (StringUtils.isNotBlank(request.getEnvironmentName())){
            pagination.getParams().put("environmentName", request.getEnvironmentName());
        }
        if (StringUtils.isNotBlank(request.getEnvironmentDesc())){
            pagination.getParams().put("environmentDesc", request.getEnvironmentDesc());
        }
        environmentDAO.selectEnvironmentPage(pagination);
        response.getPagination().setPageSize(request.getPagination().getPageSize());
        response.getPagination().setPageNo(request.getPagination().getPageNo());
        response.getPagination().setTotal(pagination.getTotal());
        response.getPagination().setPageNum(pagination.getPageNum());
        for (QueryEnvironmentInfoBO record : pagination.getRecords()) {
            response.getRecords().add(QueryEnvironmentRecord.builder()
                            .environmentId(record.getEnvironmentId())
                            .projectName(record.getGroupId() + ":" + record.getArtifactId() + ":" + record.getVersion())
                            .environmentType(record.getEnvironmentType())
                            .environmentName(record.getEnvironmentName())
                            .build()
            );
        }
        return response;
    }

    @Override
    public FetchEnvironmentResponse fetch(FetchEnvironmentRequest request) {
        FetchEnvironmentResponse response = new FetchEnvironmentResponse();
        List<EnvironmentInfoEntity> environmentEntities = environmentDAO.selectAll();
        for (EnvironmentInfoEntity environmentEntity : environmentEntities) {
            response.addItem(OptionItem.builder()
                            .text(environmentEntity.getEnvironmentName())
                            .value(environmentEntity.getEnvironmentId())
                            .build()
            );
        }
        return response;
    }

    @Override
    public ListEnvironmentByProjectResponse listEnvironmentByProject(ListEnvironmentByProjectRequest request) {
        ListEnvironmentByProjectResponse response = new ListEnvironmentByProjectResponse();
        List<ListEnvironmentInfoByProjectBO> environmentEntities = environmentDAO.listEnvironmentByProject(request.getProjectId());
        for (ListEnvironmentInfoByProjectBO record : environmentEntities) {
            response.getEnvironments().add(ListEnvironmentByProjectRecord.builder()
                            .environmentName(record.getEnvironmentName())
                            .environmentType(record.getEnvironmentType())
                            .environmentDesc(record.getEnvironmentDesc())
                            .machineCount(record.getMachineCount())
                            .build()
            );
        }
        return response;
    }
}
